package thread;

public class SyncDemo {
    public static void main(String[] args) {
        Table table = new Table();
        Thread thread = new Thread(){
            public void run (){
                while (true){
                    int bean = table.getBeans();
                    Thread.yield();
                    System.out.println(getName()+":"+bean);
                }
            }
        };
        Thread thread1 = new Thread(){
            public void run (){
                while (true){
                    int bean = table.getBeans();
                    Thread.yield();
                    System.out.println(getName()+":"+bean);
                }
            }
        };
        thread.start();
        thread1.start();
    }
}
class Table {
    private int beans = 20;
    public synchronized int getBeans(){
        if (beans == 0){
            throw new RuntimeException("没有豆子了！");
        }
        Thread.yield();//该方法可以让运行该方法的线程主动放弃本次剩余时间片
        return beans--;
    }
}